<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>{{ isLogin ? '登录' : '注册' }} - 课程管理系统</h2>
        <p>{{ isLogin ? '欢迎回来！' : '创建您的账户' }}</p>
      </div>
      
      <AuthForm 
        :mode="isLogin ? 'login' : 'register'" 
        @submit="handleSubmit"
      />
      
      <div class="auth-switch">
        <el-button 
          type="text" 
          @click="toggleMode"
        >
          {{ isLogin ? '没有账户？立即注册' : '已有账户？立即登录' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import AuthForm from '../components/AuthForm.vue'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const isLogin = ref(true)

const toggleMode = () => {
  isLogin.value = !isLogin.value
}

const handleSubmit = async (formData) => {
  try {
    if (isLogin.value) {
      // 登录逻辑
      const result = await userStore.login(formData.username, formData.pwd)
      if (result.success) {
        ElMessage.success('登录成功！')
        router.push('/home')
      } else {
        ElMessage.error(result.message || '登录失败')
      }
    } else {
      // 注册逻辑
      const result = await userStore.register(formData)
      if (result.success) {
        ElMessage.success('注册成功！请登录')
        isLogin.value = true
      } else {
        ElMessage.error(result.message || '注册失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.auth-card {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-header h2 {
  color: #303133;
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: bold;
}

.auth-header p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.auth-switch {
  text-align: center;
  margin-top: 20px;
}

.el-button--text {
  color: #409eff;
}
</style>